package com.xintoucloud.springbootguide.service;

import java.util.List;

import com.xintoucloud.springbootguide.entity.Student;
import com.xintoucloud.springbootguide.model.ResponseResult;
import com.xintoucloud.springbootguide.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
@Transactional
public class StudentService {
	@Autowired
	StudentRepository studentRespository;
	@Transactional(readOnly = true)
	public ResponseResult<Student> listStudent(int page,int limit){
		ResponseResult<Student> rr = new ResponseResult<>();
		Pageable pageable = PageRequest.of(page-1,limit, Sort.by(Sort.Order.desc("sid")));
		Page<Student> pageData = studentRespository.findAll(pageable);
		rr.setData(pageData.toList());
		rr.setMsg("success");
		rr.setCode(0);
		rr.setCount(pageData.getTotalElements());
		return rr;
	}
	
	public void deleteStudent(Integer sid) {
		studentRespository.deleteById(sid);
	}
	
	public void saveStudent(Student student) {
		studentRespository.save(student);
	}
	
	public Student getStudent(Integer sid) {
		return studentRespository.getOne(sid);
	}
	
	public void update(Student student) {
		Student studentOld = studentRespository.getOne(student.getSid());
		
		studentOld.setAddress(student.getAddress());
		studentOld.setBirthday(student.getBirthday());
		studentOld.setCardId(student.getCardId());
		studentOld.setClazz(student.getClazz());
		studentOld.setGender(student.getGender());
		studentOld.setSname(student.getSname());
		
	}
}
